package com.zhuangfei.hpuhelper.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.hpu.bean.Book;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.BookParser;
import com.hpu.parser.ScoreParser;
import com.hpu.service.BookService;
import com.hpu.service.LoginService;
import com.hpu.tools.InputMethodTools;
import com.hpu.tools.ShareTools;
import com.zhuangfei.generalpage.BaseActivity;
import com.zhuangfei.hpuhelper.tools.ActivityTools;
import com.zhuangfei.hpuhelper.tools.AssetTools;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.hpuhelper.tools.ReflectTools;
import com.zhuangfei.hpuhelper.ui.ListViewInnerScrollView;
import com.zhuangfei.smartalert.core.MessageAlert;
import com.zhuangfei.toolkit.IntentToolkit;

import cn.lzf.serviceplatform.R;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.os.Build;

public class SearchBookActivity extends BaseActivity {

	private EditText searchEditText;
	private TextView searchButton;

	private PullToRefreshListView pullToRefreshListView;
	List<Map<String, String>> items = new ArrayList<>();
	SimpleAdapter adapter;
	
	private BookService bookService;
	private LoginService loginService;
	
	private String name="";
	private int pager=1;
	private LinearLayout backLayout;

	boolean isFirstRefresh=true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_book);
		ActivityTools.setTransparent(this);
		initView();
		initEvent();
	}

	public void initView(){
		getViewHelper().showSuccessView();
		loginService=new LoginService(this,handler);
		bookService=new BookService(handler, this);
		
		searchEditText = (EditText) findViewById(R.id.id_searchbook_key);
		searchButton=(TextView) findViewById(R.id.id_search);
		backLayout=(LinearLayout) findViewById(R.id.id_back);
		pullToRefreshListView =  (PullToRefreshListView) findViewById(R.id.id_searchbook_listview);
		pullToRefreshListView.setMode(Mode.PULL_FROM_END);
		// 设置下拉刷新时显示的Label
		ILoadingLayout loadingLayout = pullToRefreshListView.getLoadingLayoutProxy(true, false);
		loadingLayout.setPullLabel("下拉刷新");
		loadingLayout.setRefreshingLabel("正在加载..");
		loadingLayout.setReleaseLabel("松开刷新");
		
		ILoadingLayout loadingLayout2 = pullToRefreshListView.getLoadingLayoutProxy(false, true);
		loadingLayout2.setPullLabel("上拉加载更多");
		loadingLayout2.setRefreshingLabel("正在加载..");
		loadingLayout2.setReleaseLabel("松开加载更多");

		pullToRefreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				isFirstRefresh=false;
				search();
			}
			
		});
		
		adapter = new SimpleAdapter(this, items, R.layout.item_book_layout, new String[] { "name","index" }, new int[] { R.id.id_book_item_name,R.id.id_book_item_index });
		pullToRefreshListView.setAdapter(adapter);

	}
	
	public void initEvent(){
		backLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				ActivityTools.toBackActivityAnim(SearchBookActivity.this, MenuActivity.class);
			}
		});
		pullToRefreshListView.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Map map = items.get(arg2-1);
				InputMethodTools.close(SearchBookActivity.this);
				new IntentToolkit().with(SearchBookActivity.this)
						.target(BookBorrowActivity.class)
						.put("id",map.get("id"))
						.put("name",map.get("name"))
						.put("index",map.get("index"))
						.ignoreFinish()
						.execute();
			}
		});
		
		searchEditText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				name=searchEditText.getText().toString();
				if(!TextUtils.isEmpty(name)){
					searchFirstPage();
				}
				else if(isFirstRefresh){
					getViewHelper().showSuccessView();
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});
		
		searchButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {

				name=searchEditText.getText().toString();
				if(!TextUtils.isEmpty(name)){
					InputMethodTools.close(SearchBookActivity.this);
					searchFirstPage();
				}

			}
		});
	}

	public void searchFirstPage() {
		pager=1;
		items.clear();
		isFirstRefresh=true;
		search();
	}

	public void search() {
		if (name != null &&!name.equals("")){
			if(isFirstRefresh){
				getViewHelper().showLoadingView();
			}
			bookService.getBooks(name,pager+"");

		}
	}


	DefaultHandler handler = new DefaultHandler(this) {
		public void handleMessage(Message msg) {
			pullToRefreshListView.onRefreshComplete();
			if(isFirstRefresh){
				getViewHelper().showSuccessView();
			}

			super.handleMessage(msg);

			switch (msg.what) {
			case HttpConstants.QUERY_BOOK_SUCCESS:
				Log.i("Book",msg.obj.toString());
				BookParser bookParser=new BookParser();
				List<Book> books=bookParser.parse(msg.obj.toString());
				showBooks(books);
				pager=pager+1;
				break;

			// VPN过期
			case HttpConstants.VPN_TOOLONG:
				if(handler.isIgnoreVpnExpired()){
					break;
				}
				if(isFirstRefresh){
					getViewHelper().showLoadingView();
				}
				loginService.login(ShareTools.get(SearchBookActivity.this, ShareConstants.STORE_USER, "").toString(),
						ShareTools.get(SearchBookActivity.this, ShareConstants.STORE_PASSWORD1, "").toString(),
						ShareTools.get(SearchBookActivity.this, ShareConstants.STORE_PASSWORD2, "").toString());
				break;

			// 登录成功
			case HttpConstants.LOGIN_SUCCESS:
				ShareTools.put(SearchBookActivity.this, ShareConstants.STORE_LOGINCOOKIE, (String) msg.obj);
				search();
				break;

			}
		};
	};

	protected void showBooks(List<Book> books) {
		if(books.size()<=0) return;
		int preSize=items.size();
		for(int i=0;i<books.size();i++){
			Book book=books.get(i);
			Map<String, String> map=new HashMap<>();
			map.put("name", book.getName());
			map.put("index",book.getIndex());
			map.put("id",book.getId());
			items.add(map);
		}

		if(preSize>0&&(items.size()>(preSize+2))){
			pullToRefreshListView.getRefreshableView().setSelection(preSize+2);
		}
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void onBackPressed() {
		ActivityTools.toBackActivityAnim(this, MenuActivity.class);
	}
}
